package com.galeno.day06;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2210:39
 */
public class StateUseFlinkAPI {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",55555);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        env.enableCheckpointing(10000);
        DataStreamSource<String> lines = env.socketTextStream("galeno", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> tup = lines.map(x -> {
            String[] split = x.split(",");
            if (split[0].contains("error")){
                throw new RuntimeException("报错了");
            }
            return Tuple2.of(split[0], Integer.parseInt(split[1]));
        }).returns(TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {
        }));
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = tup.keyBy(x -> x.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> mapstate = keyedStream.map(new RichMapFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
           private ValueState<Integer> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<Integer> integerValueStateDescriptor = new ValueStateDescriptor<>("count-state", Integer.class);
                valueState = getRuntimeContext().getState(integerValueStateDescriptor);
            }

            @Override
            public Tuple2<String, Integer> map(Tuple2<String, Integer> in) throws Exception {
                String word = in.f0;
                Integer count = in.f1;

                Integer histroryCount = valueState.value();
                if (histroryCount==null){
                    histroryCount=0;
                }
                int totalCount = histroryCount + count;
                valueState.update(totalCount);
                in.f1=totalCount;
                return in;
            }
        });
        mapstate.print();
        env.execute();



    }
}
